<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

use Illuminate\Bus\Queueable as Queueables;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\User;

class UpdateUserBalance implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $userId;
    protected $amount;

    /**
     * Create a new job instance.
     */
    public function __construct($userId, $amount)
    {
        $this->userId = $userId;
        $this->amount = $amount;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 检查任务是否已经处理过（例如，通过检查数据库中的某个标记）
        $lockKey = "user_balance_update_{$this->userId}_lock";

        if (cache()->has($lockKey)) {
            // 任务已经在处理中，不再重复处理
            return;
        }

        // 锁定任务以避免并发处理
        cache()->put($lockKey, true, 3600); // 锁定时间根据需要设置

        // 更新用户余额逻辑
        $user = User::findOrFail($this->userId);
        $user->balance += $this->amount;
        $user->save();

        // 释放锁
        cache()->forget($lockKey);
    }
}
